var login_vm = new Vue({
    el: '.login-container',
    data: {
        user:null,
        formData: {
            username: null,
            password: null
        },
        inputType: 'password',
        hasError: false
    },
    computed:{
        hasPermission(){
            if(this.user){
                var administrators = ['admin','director']
                // var staff = [,'deputy_director','principal','main_principal','staff']
                return _.indexOf(administrators,this.user.roles[0].name)!==-1
            }
        },
        canLogin(){
            return this.formData.username && this.formData.password
        }
    },
    methods: {
        toggleInput() {
            this.inputType == 'password' ? this.inputType = 'text' : this.inputType = 'password'
        },
        login() {
            if(!this.canLogin){
                return;
            }
            var target = event.currentTarget
            $(target).button('loading');
            var self = this
            axios.post(window.config.host + '/login', this.formData)
                .then(function(res) {
                    if (res.status == 200) {
                        if(res.data.data.accessToken){
                            self.user = res.data.data.user
                            localStorage.token = res.data.data.accessToken
                            localStorage.userinfo = JSON.stringify(res.data.data.user)
                            Cookies.set('token', res.data.data.accessToken)
                            Cookies.set('userinfo', JSON.stringify(res.data.data.user))
                            self.hasError = false
                            self.goDashboard()
                        }else{
                            self.hasError = true
                            alert(res.data.data.message)
                        }
                    } else {
                        alert(res.data.message)
                    }
                }).catch(function(err) {

                }).then(function(){
                     $(target).button('reset');
                })
        },
        goDashboard(){
            this.hasPermission ? window.location.href = '/department' : window.location.href = '/years' 
        }
    }
})